<<template>
	<view class="check-form">
		<!-- 表单标题 -->
		<view class="form-header">
			<text class="form-title">入库验收单</text>
			<view class="form-code">
				<text>验收编号：{{ checkForm.checkId }}</text>
				<text style="margin-left: 30rpx;">关联申请单：{{ checkForm.applyId }}</text>
			</view>
		</view>

		<!-- 基本信息区 -->
		<view class="form-section">
			<view class="section-title">基本信息</view>
			<view class="form-row">
				<view class="form-col-4">
					<view class="form-label">供应商</view>
					<view class="form-input disable">{{ checkForm.supplierName }}</view>
				</view>
				<view class="form-col-4">
					<view class="form-label">仓库</view>
					<view class="form-input disable">{{ checkForm.warehouseName }}</view>
				</view>
				<view class="form-col-4">
					<view class="form-label">申请日期</view>
					<view class="form-input disable">{{ checkForm.applyDate }}</view>
				</view>
			</view>
			<view class="form-row">
				<view class="form-col-4">
					<view class="form-label">验收日期</view>
					<uni-datetime-picker type="date" v-model="checkForm.checkDate" @change="onDateChange" />
				</view>
				<view class="form-col-4">
					<view class="form-label">验收人</view>
					<view class="form-input disable">{{ checkForm.checkUser }}</view>
				</view>
				<view class="form-col-4">
					<view class="form-label">申请人</view>
					<view class="form-input disable">{{ checkForm.applyUser }}</view>
				</view>
			</view>
		</view>

		<!-- 商品验收明细区 -->
		<view class="form-section">
			<view class="section-title">商品验收明细</view>
			<!-- 商品标题 -->
			<view class="table-header">
				<view class="th th-1">商品名称</view>
				<view class="th th-2">规格型号</view>
				<view class="th th-3">单位</view>
				<view class="th th-4">申请数量</view>
				<view class="th th-5">实际验收数量</view>
				<view class="th th-6">质量状况</view>
				<view class="th th-7">不合格原因</view>
				<view class="th th-8">处理方式</view>
			</view>

			<view class="table-body" v-for="(item, index) in checkForm.items" :key="index">
				<view class="table-row">
					<view class="td td-1">
						<view class="disable">{{ item.goodName }}</view>
					</view>
					<view class="td td-2">
						<view class="disable">{{ item.spec.specStr || '无规格' }}</view>
					</view>
					<view class="td td-3">
						<view class="disable">{{ item.unit.unitName }}</view>
					</view>
					<view class="td td-4">
						<view class="disable">{{ item.applyQuantity }}</view>
					</view>
					<view class="td td-5">
						<input 
							v-model.number="item.checkQuantity" 
							placeholder="输入实际数量" 
							class="table-input" 
							type="number"
							@input="calcTotal"
						/>
					</view>
					<view class="td td-6">
						<radio-group v-model="item.qualityStatus" @change="onQualityChange(index)">
							<label class="radio-item">
								<radio :value="1" />
								<text>合格</text>
							</label>
							<label class="radio-item">
								<radio :value="0" />
								<text>不合格</text>
							</label>
						</radio-group>
					</view>
					<view class="td td-7">
						<textarea 
							v-model="item.unqualifiedReason" 
							placeholder="如不合格请说明原因" 
							class="table-textarea"
							:disabled="item.qualityStatus === 1"
						></textarea>
					</view>
					<view class="td td-8">
						<picker 
							mode="selector" 
							:range="handleOptions" 
							v-model="item.handleType"
							:disabled="item.qualityStatus === 1"
						>
							<view class="picker-view">
								{{ item.handleType === -1 ? '选择处理方式' : handleOptions[item.handleType] }}
							</view>
						</picker>
					</view>
				</view>
			</view>

			<view class="total-row">
				<view class="total-col" colspan="5">
					<text>总验收商品：{{ checkForm.items.length }} 项</text>
					<text style="margin-left: 30rpx;">合格：{{ qualifiedCount }} 项</text>
					<text style="margin-left: 30rpx;">不合格：{{ unqualifiedCount }} 项</text>
				</view>
				<view class="total-col" colspan="3">
					<text>实际验收总数：{{ totalCheckQuantity }}</text>
				</view>
			</view>
		</view>

		<!-- 验收结果区 -->
		<view class="form-section">
			<view class="section-title">验收结论</view>
			<view class="form-row">
				<view class="form-col-12">
					<radio-group v-model="checkForm.finalResult" class="result-radio">
						<label class="result-item">
							<radio :value="1" />
							<text>全部合格</text>
						</label>
						<label class="result-item">
							<radio :value="2" />
							<text>部分合格</text>
						</label>
						<label class="result-item">
							<radio :value="3" />
							<text>全部不合格</text>
						</label>
					</radio-group>
				</view>
			</view>
		</view>

		<!-- 备注信息区 -->
		<view class="form-section">
			<view class="section-title">验收附件及备注</view>
			<view class="form-row">
				<view class="form-col-12">
					<view class="form-label">
						<text>验收附件</text>
						<button type="primary" size="mini" @click="chooseAttach">上传</button>
						<text style="font-size: 24rpx;">(支持验收照片、质检报告等，格式：png、jpg、pdf)</text>
					</view>
					<view class="attach-list">
						<view class="attach-item" v-for="(file, i) in checkForm.attachments" :key="i">
							<text class="file-name">{{ file.name }}</text>
							<text class="file-size">{{ file.size }}</text>
							<text class="file-delete" @click="deleteAttach(i)">×</text>
						</view>
					</view>
				</view>
			</view>
			<view class="form-row">
				<view class="form-col-12">
					<view class="form-label">验收备注</view>
					<textarea 
						v-model="checkForm.checkRemark" 
						placeholder="请输入验收过程中的特殊情况说明" 
						class="form-textarea" 
						rows="3"
					></textarea>
				</view>
			</view>
		</view>

		<!-- 操作按钮区 -->
		<view class="form-actions">
			<button class="btn btn-primary" @click="submitCheck">提交验收结果</button>
			<button class="btn btn-secondary" @click="resetCheck">重置</button>
		</view>
	</view>
</template>

<script>
import UniDatetimePicker from '../../uni_modules/uni-datetime-picker/components/uni-datetime-picker/uni-datetime-picker.vue';
import { store } from '../../uni_modules/uni-id-pages/common/store.js';
import { errForm } from '../../untils/errForm';
const db = uniCloud.database();
const CouldDb = uniCloud.importObject('getDb');

export default {
	name: 'StockCheck',
	components: {
		UniDatetimePicker
	},
	props: {
		// 接收从申请单传递的基础数据
		applyData: {
			type: Object,
			default: () => ({})
		}
	},
	data() {
		const today = new Date();
		const year = today.getFullYear();
		const month = (today.getMonth() + 1).toString().padStart(2, '0');
		const day = today.getDate().toString().padStart(2, '0');
		const randomNum = Math.floor(1000 + Math.random() * 9000);

		return {
			// 处理方式选项
			handleOptions: ['退货', '返工', '让步接收', '销毁', '其他'],
			checkForm: {
				checkId: `CK-${year}${month}${day}-${randomNum}`, // 验收单编号
				applyId: '', // 关联申请单编号
				supplierName: '', // 供应商名称
				warehouseName: '', // 仓库名称
				applyDate: '', // 申请日期
				checkDate: `${year}-${month}-${day}`, // 验收日期
				checkUser: '', // 验收人
				applyUser: '', // 申请人
				finalResult: 1, // 最终结论 1-全部合格 2-部分合格 3-全部不合格
				checkRemark: '', // 验收备注
				attachments: [], // 验收附件
				items: [] // 验收商品明细
			},
			totalCheckQuantity: 0, // 总验收数量
			qualifiedCount: 0, // 合格项数
			unqualifiedCount: 0 // 不合格项数
		};
	},
	computed: {
		userInfo() {
			return store.userInfo || {};
		}
	},
	watch: {
		applyData: {
			immediate: true,
			handler(val) {
				// 初始化验收单数据（从申请单同步）
				if (val.applyItem && val.items && val.items.length) {
					this.checkForm.applyId = val.applyItem.applyForId;
					this.checkForm.supplierName = val.ownership[val.ownershipValue]?.supplier_name || '';
					this.checkForm.warehouseName = val.warehouseList[val.warehouserValue]?.warehouse_name || '';
					this.checkForm.applyDate = val.applyItem.applyDate;
					this.checkForm.applyUser = val.userInfo?.username || '';
					this.checkForm.checkUser = this.userInfo.username || '';

					// 初始化商品明细（复制申请单商品信息）
					this.checkForm.items = val.items.map(item => ({
						productId: item.productId,
						goodName: item.goodName,
						spec: item.spec,
						unit: item.unit,
						applyQuantity: item.quantity || 0, // 申请数量
						checkQuantity: 0, // 实际验收数量
						qualityStatus: 1, // 质量状况 1-合格 0-不合格
						unqualifiedReason: '', // 不合格原因
						handleType: -1 // 处理方式（默认未选择）
					}));
				}
			}
		}
	},
	methods: {
		// 计算验收总数和合格/不合格项数
		calcTotal() {
			// 计算总验收数量
			this.totalCheckQuantity = this.checkForm.items.reduce((sum, item) => {
				return sum + (item.checkQuantity || 0);
			}, 0);

			// 计算合格/不合格项数
			this.qualifiedCount = this.checkForm.items.filter(item => item.qualityStatus === 1).length;
			this.unqualifiedCount = this.checkForm.items.length - this.qualifiedCount;

			// 自动更新最终结论（根据实际情况可手动修改）
			if (this.qualifiedCount === this.checkForm.items.length) {
				this.checkForm.finalResult = 1;
			} else if (this.qualifiedCount === 0) {
				this.checkForm.finalResult = 3;
			} else {
				this.checkForm.finalResult = 2;
			}
		},

		// 质量状况变更
		onQualityChange(index) {
			const item = this.checkForm.items[index];
			// 合格时清空不合格原因和处理方式
			if (item.qualityStatus === 1) {
				item.unqualifiedReason = '';
				item.handleType = -1;
			}
			this.calcTotal();
		},

		// 选择验收附件
		// 删除附件
		deleteAttach(index) {
			this.checkForm.attachments.splice(index, 1);
		},

		// 格式化文件大小
		formatSize(bytes) {
			if (bytes === 0) return '0 B';
			const k = 1024;
			const sizes = ['B', 'KB', 'MB', 'GB'];
			const i = Math.floor(Math.log(bytes) / Math.log(k));
			return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
		},

		// 日期变更
		onDateChange(e) {
			this.checkForm.checkDate = e;
		},

		// 提交验收单
		submitCheck() {
			// 表单验证
			const errItems = [];
			// 验证商品验收数量
			this.checkForm.items.forEach((item, index) => {
				if (item.checkQuantity <= 0) {
					errItems.push(`第${index + 1}行商品未填写验收数量`);
				}
				// 验证不合格商品的原因和处理方式
				if (item.qualityStatus === 0) {
					if (!item.unqualifiedReason) {
						errItems.push(`第${index + 1}行不合格商品未填写原因`);
					}
					if (item.handleType === -1) {
						errItems.push(`第${index + 1}行不合格商品未选择处理方式`);
					}
				}
			});

			// 验证最终结论
			if (!this.checkForm.finalResult) {
				errItems.push('请选择验收最终结论');
			}

			// 显示错误信息
			if (errItems.length > 0) {
				uni.showModal({
					title: '验收信息不完整',
					content: errItems.join('\n'),
					showCancel: false
				});
				return;
			}

			// 提交确认
			uni.showModal({
				title: '确认提交',
				content: '确定提交入库验收结果吗？',
				success: async (res) => {
					if (res.confirm) {
						uni.showLoading({ title: '提交中...', mask: true });
						try {
							// 准备提交数据（包含附件上传逻辑）
							const submitData = {
								...this.checkForm,
								submitTime: new Date().getTime()
							};

							// 模拟附件上传（实际项目中需调用上传接口）
							if (this.checkForm.attachments.length) {
								const uploadPromises = this.checkForm.attachments.map(file => {
									return new Promise((resolve) => {
										// 模拟上传成功，返回文件URL
										setTimeout(() => {
											resolve(`https://your-upload-url/${file.name}`);
										}, 500);
									});
								});
								const attachUrls = await Promise.all(uploadPromises);
								submitData.attachments = attachUrls;
							}

							// 提交验收单数据到数据库
							const result = await CouldDb.addDB('StockCheck', submitData);
							if (result.code) {
								uni.showToast({ title: '验收单提交成功', icon: 'success', duration: 2000 });
								// 提交成功后返回上一页
								setTimeout(() => {
									uni.navigateBack();
								}, 1500);
							}
						} catch (error) {
							console.error('验收单提交失败:', error);
							uni.showToast({ title: '提交失败，请重试', icon: 'none' });
						} finally {
							uni.hideLoading();
						}
					}
				}
			});
		},

		// 重置表单
		resetCheck() {
			this.checkForm.items.forEach(item => {
				item.checkQuantity = 0;
				item.qualityStatus = 1;
				item.unqualifiedReason = '';
				item.handleType = -1;
			});
			this.checkForm.finalResult = 1;
			this.checkForm.checkRemark = '';
			this.checkForm.attachments = [];
			this.calcTotal();
		},

		// 选择附件
		chooseAttach() {
			uni.chooseImage({
				count: 5,
				sizeType: ['original', 'compressed'],
				sourceType: ['album', 'camera'],
				success: (res) => {
					const newFiles = res.tempFiles.map(file => ({
						name: file.name,
						path: file.path,
						size: this.formatSize(file.size)
					}));
					this.checkForm.attachments = [...this.checkForm.attachments, ...newFiles];
				}
			});
		}
	}
};
</script>

<style scoped>
/* 基础样式复用申请单风格，仅修改特有样式 */
.check-form {
	padding: 20rpx;
	background-color: #f5f5f5;
	min-height: 100vh;
	width: 100%;
}

.form-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 30rpx;
	padding: 20rpx;
	background-color: #fff;
	border-radius: 8rpx;
}

.form-title {
	font-size: 36rpx;
	font-weight: bold;
	color: #333;
}

.form-code {
	font-size: 26rpx;
	color: #666;
	display: flex;
}

.form-section {
	background-color: #fff;
	border-radius: 8rpx;
	padding: 20rpx;
	margin-bottom: 30rpx;
}

.section-title {
	font-size: 30rpx;
	font-weight: bold;
	color: #333;
	padding: 10rpx 0;
	border-bottom: 1rpx solid #eee;
	margin-bottom: 20rpx;
}

.form-row {
	display: flex;
	flex-wrap: wrap;
	margin-bottom: 20rpx;
}

.form-col-4, .form-col-6, .form-col-12 {
	padding: 0 10rpx;
	box-sizing: border-box;
}

.form-col-4 {
	width: 33.333%;
}

.form-col-6 {
	width: 50%;
}

.form-col-12 {
	width: 100%;
}

.form-label {
	font-size: 28rpx;
	color: #666;
	margin-bottom: 10rpx;
	display: flex;
	align-items: center;
}

.form-input, .disable {
	width: 100%;
	padding: 16rpx 20rpx;
	border: 1rpx solid #e5e6eb;
	border-radius: 8rpx;
	font-size: 28rpx;
	color: #333;
	background-color: #f8f8f8;
}

.disable {
	background-color: #f5f5f5;
	color: #666;
}

.table-header {
	display: flex;
	background-color: #f5f7fa;
	border-radius: 8rpx 8rpx 0 0;
	overflow: hidden;
}

.th {
	padding: 15rpx 10rpx;
	font-size: 26rpx;
	font-weight: bold;
	color: #666;
	text-align: center;
	border-right: 1rpx solid #eee;
	display: flex;
	align-items: center;
	justify-content: center;
}

.th-1 { width: 15%; }
.th-2 { width: 15%; }
.th-3 { width: 8%; }
.th-4 { width: 10%; }
.th-5 { width: 12%; }
.th-6 { width: 10%; }
.th-7 { width: 15%; }
.th-8 { width: 15%; }

.table-body {
	border: 1rpx solid #eee;
	border-top: none;
}

.table-row {
	display: flex;
}

.td {
	padding: 15rpx 10rpx;
	font-size: 26rpx;
	color: #333;
	border-right: 1rpx solid #eee;
	border-bottom: 1rpx solid #eee;
	box-sizing: border-box;
}

.td-1 { width: 15%; }
.td-2 { width: 15%; }
.td-3 { width: 8%; }
.td-4 { width: 10%; }
.td-5 { width: 12%; }
.td-6 { width: 10%; }
.td-7 { width: 15%; }
.td-8 { width: 15%; }

.table-input {
	width: 100%;
	padding: 8rpx 10rpx;
	border: 1rpx solid #e5e6eb;
	border-radius: 4rpx;
	font-size: 26rpx;
	text-align: center;
}

.table-textarea {
	width: 100%;
	height: 100rpx;
	padding: 10rpx;
	border: 1rpx solid #e5e6eb;
	border-radius: 4rpx;
	font-size: 24rpx;
	resize: none;
}

.radio-item {
	display: flex;
	align-items: center;
	margin-right: 40rpx;
	font-size: 28rpx;
}

.radio-item radio {
	transform: scale(0.8);
	margin-right: 10rpx;
}

.result-radio {
	display: flex;
	padding: 20rpx 0;
}

.result-item {
	display: flex;
	align-items: center;
	margin-right: 60rpx;
	font-size: 28rpx;
}

.result-item radio {
	transform: scale(0.9);
	margin-right: 15rpx;
}

.attach-list {
	display: flex;
	flex-wrap: wrap;
	margin-top: 15rpx;
}

.attach-item {
	display: flex;
	align-items: center;
	padding: 10rpx 15rpx;
	background-color: #f5f7fa;
	border-radius: 4rpx;
	margin-right: 15rpx;
	margin-bottom: 15rpx;
	font-size: 24rpx;
}

.file-name {
	color: #333;
	max-width: 200rpx;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.file-size {
	color: #999;
	margin-left: 10rpx;
}

.file-delete {
	color: #f53f3f;
	margin-left: 15rpx;
	font-size: 28rpx;
}

.picker-view {
	width: 100%;
	padding: 16rpx 20rpx;
	border: 1rpx solid #e5e6eb;
	border-radius: 8rpx;
	font-size: 28rpx;
	color: #333;
	position: relative;
}

.picker-view::after {
	content: "\f078";
	font-family: "FontAwesome";
	position: absolute;
	right: 20rpx;
	top: 50%;
	transform: translateY(-50%);
	color: #86909c;
	font-size: 24rpx;
}

.form-textarea {
	width: 100%;
	padding: 16rpx 20rpx;
	border: 1rpx solid #e5e6eb;
	border-radius: 8rpx;
	font-size: 28rpx;
	color: #333;
	min-height: 120rpx;
	resize: none;
}

.form-actions {
	display: flex;
	justify-content: center;
	margin-top: 40rpx;
	margin-bottom: 60rpx;
}

.btn {
	width: 280rpx;
	height: 88rpx;
	line-height: 88rpx;
	border-radius: 44rpx;
	font-size: 32rpx;
	margin: 0 20rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.btn-primary {
	background-color: #165dff;
	color: #fff;
}

.btn-secondary {
	background-color: #f5f7fa;
	color: #4e5969;
	border: 1rpx solid #e5e6eb;
}

.total-row {
	display: flex;
	padding: 20rpx;
	background-color: #f5f7fa;
	border-top: 1rpx solid #eee;
}

.total-col {
	font-size: 26rpx;
	color: #333;
}
</style>